package com.tduck.cloud.datav.service.charts;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import com.google.common.collect.Lists;
import com.tduck.cloud.datav.constant.ChartsConstants;
import com.tduck.cloud.datav.request.ChartDataRequest;
import com.tduck.cloud.datav.vo.EchartsIndicatorVO;
import com.tduck.cloud.datav.vo.EchartsSeriesVO;
import com.tduck.cloud.datav.vo.GroupQueryResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class BasicRadarChartDataService extends PercentPondChartDataService {


    @Override
    public Map<String, Object> getChartData(ChartDataRequest request) {
        GroupQueryResult groupQueryResult = this.getGroupQueryDataList(request);
        Map<String, Object> result = MapUtil.of();
        List<EchartsIndicatorVO> indicatorVOList = groupQueryResult.getGroupDataList().stream().map(item -> new EchartsIndicatorVO(item, 0)).collect(Collectors.toList());
        Map<String, List<Object>> groupAggsMap = groupQueryResult.getGroupAggsMap();
        List<EchartsSeriesVO> seriesVOList = groupAggsMap.keySet().stream().map(key -> {
            List<Object> values = groupAggsMap.get(key);
            List<Object> seriesItemList = Lists.newArrayList();
            // 计算雷达最大值
            for (int i = 0; i < values.size(); i++) {
                Integer convert = Convert.convert(Integer.class, values.get(i));
                CollUtil.get(indicatorVOList, i).setMax(Math.max(convert, CollUtil.get(indicatorVOList, i).getMax()));

            }
            EchartsSeriesVO.SeriesItem seriesItem = new EchartsSeriesVO.SeriesItem();
            request.getIndex().stream().filter(item -> key.startsWith(item.getId())).findFirst().ifPresent(item -> seriesItem.setName(item.getLabel()));
            seriesItem.setValue(values);
            seriesItemList.add(seriesItem);
            return new EchartsSeriesVO(key, seriesItemList);
        }).collect(Collectors.toList());
        // 最大值增加10%
        result.put(ChartsConstants.INDICATOR, indicatorVOList.stream().map(item -> {
            item.setMax((int) (item.getMax() * 1.1));
            return item;
        }).collect(Collectors.toList()));
        result.put(ChartsConstants.SERIES, seriesVOList);
        return result;
    }
}
